<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        html,
        body {
            height: 100%;
            margin: 0;
        }

        input {
            width: 500px;
            height: 100px;
            margin: 0 auto;
            display: block;
            font-size: 20px;
        }
    </style>
</head>

<body>
    <input id="inputBox" value="0123[tao]+[test]0123">

    <script>
        //[123]+[78]+[11]
        let inputBox = document.getElementById('inputBox');
        inputBox.addEventListener('keydown', function (event) {
            let key = event.key
            // 获取输入框的值
            let text = inputBox.value;
            // 获取光标起始位置和结束位置
            let selectionStart = inputBox.selectionStart;
            // let selectionEnd = inputBox.selectionEnd;
            
            // 判断光标所在位置是否处于方括号内
            if (isCursorInsideBrackets(text, selectionStart)) {
                event.preventDefault(); // 阻止输入
            }
            if(key === "Backspace" || key === "Delete") {
                console.log(text[selectionStart-1]);
                if(text[selectionStart-1] == '[' || text[selectionStart-1] == ']') {
                    event.preventDefault();
                }
            }
        });


        // 检查光标位置是否在方括号内
        function isCursorInsideBrackets(text, position) {
            // 找到距离当前位置前面最近的符号 [ 或者 ] "This[tao]+[test]string"
            let leftBracketIndex = -Infinity;
            let rightBracketIndex = Infinity;
            for(let i = position; i >= 0; i--) {
                if(text[i] == '[' || text[i] == ']') {
                    leftBracketIndex = i;
                    break;
                }
            }
            for(let j = position; j < text.length; j++) {
                if(text[j] == ']' || text[j] == '[') {
                    rightBracketIndex = j;
                    break;
                }
            }
            // console.log('左坐标：'+leftBracketIndex,'右坐标：'+rightBracketIndex);
            // console.log('左边：'+text[leftBracketIndex],'右边：'+text[rightBracketIndex]);
            if((text[leftBracketIndex] == '[' && text[rightBracketIndex] == ']') ||  (text[leftBracketIndex] == ']' && text[rightBracketIndex] == ']')) {
                return true
            } else {
                return false
            }
        }
    </script>

</body>

</html>